package com.huaweicloud.commons.outhUtils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

@Data
@Getter
@Setter
@Component
/**
 * JWT 认证工具类，Token获取和Token解析
 */
public class JwtUtil {

    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    private static final int ttl = 3600000;

    /**
     * 签发Token
     *
     * @param id  请求用户id
     * @param map 关键用户信息保存到map中
     * @return token 返回生产的用户token
     */
    public String getToken(String id, Map<String, String> map) {

        SecretKey secretKey = generalKey();
        long now = System.currentTimeMillis();
        long exp = now + ttl;
        String token;

        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setIssuedAt(new Date())
                .signWith(secretKey, signatureAlgorithm);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            builder.claim(entry.getKey(), entry.getValue());
        }

        builder.setExpiration(new Date(exp));

        token = builder.compact();
        return token;
    }

    /**
     * 解析Token
     *
     * @param token 用户token
     * @return Claims 返回 jwt Claims
     */
    public Claims parseToken(String token) {
        SecretKey secretKey = generalKey();
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(token).getBody();
        return claims;
    }

    public static SecretKey generalKey() {

        SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode("cuAihCz53DZRjZwbsGcZJ2Ai6At+T142uphtJMsk7iQ="));
        return key;
    }
}
